package com.lmx.project.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.PageRequest;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.studyrecords.StudyrecordsAddRequest;
import com.lmx.project.model.dto.studyrecords.StudyrecordsQueryRequest;
import com.lmx.project.model.entity.Studyrecords;
import com.lmx.project.model.enums.FileDir;
import com.lmx.project.model.vo.studyRecord.StudyrecordsShareVO;
import com.lmx.project.model.vo.studyRecord.StudyrecordsVo;
import com.lmx.project.model.vo.UsersVo;
import com.lmx.project.service.StudyrecordsService;
import com.lmx.project.mapper.StudyrecordsMapper;
import com.lmx.project.service.UsersService;
import com.lmx.project.untils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Lenovo
 * @description 针对表【studyRecords(学习记录表)】的数据库操作Service实现
 * @createDate 2023-04-07 22:36:34
 */
@Service
@Slf4j
public class StudyrecordsServiceImpl extends ServiceImpl<StudyrecordsMapper, Studyrecords>
        implements StudyrecordsService {


    @Resource
    private StudyrecordsMapper studyrecordsMapper;

    @Resource
    private FileUtil fileUtil;
    @Resource
    private UsersService usersService;


    private String studyPre = "study:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Page<StudyrecordsVo> getstudurecordsByCondition(StudyrecordsQueryRequest studyrecordsQueryRequest) {

        long current = studyrecordsQueryRequest.getCurrent();
        long pageSize = studyrecordsQueryRequest.getPageSize();

        current = (current - 1) * pageSize;

        studyrecordsQueryRequest.setCurrent(current);
//     查询总数
        Long count = studyrecordsMapper.countStudyrecord(studyrecordsQueryRequest);
//         先查询条件
        List<StudyrecordsVo> list = studyrecordsMapper.selectstudurecords(studyrecordsQueryRequest);

        Page<StudyrecordsVo> studyrecordsPage = new Page<>();

        studyrecordsPage.setRecords(list);

        studyrecordsPage.setTotal(count);


        return studyrecordsPage;

    }

    @Override
    public Long addRecord(StudyrecordsAddRequest studyrecordsAddRequest, HttpServletRequest request) {

        if (studyrecordsAddRequest.getLearningcontent() == null || studyrecordsAddRequest.getLearningcontent().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写学习内容");
        }

        if (studyrecordsAddRequest.getAddStudyFile() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请上传文件");
        }


        Studyrecords studyrecords = new Studyrecords();
        BeanUtils.copyProperties(studyrecordsAddRequest, studyrecords);

//        保存文件
        if (studyrecordsAddRequest.getAddStudyFile() != null) {
            MultipartFile addAvatarFile = studyrecordsAddRequest.getAddStudyFile();

            final String originalFilename = addAvatarFile.getOriginalFilename();
            String prefix = originalFilename.substring(originalFilename.lastIndexOf(".")); //后缀
//                获取当前的时间

            Date date = new Date();
            long time = date.getTime();
            String b = fileUtil.saveMultipartFile(addAvatarFile, FileDir.STUDYDIR);
            if (b != null) {
                studyrecords.setFileurl(b);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件上传错误，请重试");
            }
        }


//        获取当前登录用户
//        BaseResponse<Users> usersByid = usersController.getUsersByid(request);
        UsersVo usersVo = usersService.getUserCurrent(request);
        if (usersVo == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请先登录");
        }
        Long id = usersVo.getId();
        studyrecords.setUserid(id);
        boolean save = save(studyrecords);
//      将提交记录的id保存到缓存中
//      计算当前时间与午夜0点的时间差值
        long secondsUntilNextDay = getSecondsUntilNextDay();
        stringRedisTemplate.opsForValue().set(studyPre + id, studyrecords.getId().toString()
                , secondsUntilNextDay, TimeUnit.SECONDS);

        return studyrecords.getId();

    }

    @Override
    public String isCommit(HttpServletRequest request) {
        UsersVo userCurrent = usersService.getUserCurrent(request);
        final Long userid = userCurrent.getId();

//        保存的是提交记录编号
        String s = stringRedisTemplate.opsForValue().get(studyPre + userid);
        return s;
    }

    @Override
    public Boolean removeRecord(Long id, HttpServletRequest request) {
        UsersVo userCurrent = usersService.getUserCurrent(request);
        Long userid = userCurrent.getId();
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Studyrecords byId = getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该记录不存在");
        }
//        删除云存储中的图片
        String fileurl = byId.getFileurl();
//        String[] split = fileurl.split("/");
//        String key = split[split.length - 2] + "/" + split[split.length - 1];
        fileUtil.removeFile(fileurl);

//        删除数据库中的记录
        boolean b = removeById(id);
//        删除缓存中的记录
        stringRedisTemplate.delete(studyPre + userid);
        return b;
    }

    @Override
    public Page<StudyrecordsShareVO> getShareRecordVo(PageRequest pageRequest) {
        long current = pageRequest.getCurrent();
        long pageSize = pageRequest.getPageSize();

        current = (current - 1) * pageSize;

        pageRequest.setCurrent(current);
//     查询总数
        Long count = studyrecordsMapper.countSharerecord();
//         先查询条件
        List<StudyrecordsShareVO> list = studyrecordsMapper.selectShareRecords(pageRequest);

        Page<StudyrecordsShareVO> studyrecordsPage = new Page<>();

        studyrecordsPage.setRecords(list);

        studyrecordsPage.setTotal(count);

        return studyrecordsPage;

    }

    /**
     * 获取当前时间与0点的时间差值
     *
     * @return
     */
    public static long getSecondsUntilNextDay() {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime nextDayMidnight = currentTime.plus(1, ChronoUnit.DAYS)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
        Duration duration = Duration.between(currentTime, nextDayMidnight);
        return duration.getSeconds();
    }
}




